<template>
  <el-form ref="formRef" :model="form" labelWidth="120px" label-suffix="：">
    <el-steps :active="active">
      <template v-for="(step, index) in steps" :key="index">
        <el-step>
          <template #title>
            <span class="step-title" @click="active = step.value">{{ step.title }}</span>
          </template>
        </el-step>
      </template>
    </el-steps>

    <div v-show="active === 1" class="step1">
      <el-form-item label="节点名称">
        <el-input v-model="form.nodeName"/>
      </el-form-item>
      <el-form-item label="节点ID">
        <el-input v-model="form.typeConcatName" disabled/>
      </el-form-item>
      <el-form-item label="数据库源" prop="datasourceId">
        <el-select v-model="form.datasourceId" @change="rDsChange" filterable style="width: 100%"
                   :loading="loading">
          <el-option
              v-for="item in rDsList" :key="item.datasourceId"
              :label="item.datasourceGroup + '_' + item.datasourceName + '_' + item.datasourceType"
              :value="item.datasourceId"/>
        </el-select>
      </el-form-item>
      <el-form-item
          v-show="form.datasourceType==='postgresql' || form.datasourceType==='oracle' ||form.datasourceType==='sqlserver'"
          label="Schema">
        <el-select v-model="form.schema" filterable style="width: 100%" @change="schemaChange">
          <el-option
              v-for="item in schemaList"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据库表名" prop="table">
        <el-select v-model="form.table" default-first-option filterable style="width: 100%" :loading="loading"
                   @change="rTbChange">
          <el-option v-for="item in rTbList" :key="item" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="运行状态">
        <el-radio-group v-model="form.execute_each_row" @change="console.log(form.execute_each_row)">
          <el-radio label="N">仅执行一次</el-radio>
          <el-radio label="Y">对数据记录逐条执行SQL</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="流输出" prop="isStream">
        <el-switch v-model="form.isStream" active-value="Y" inactive-value="N"></el-switch>
      </el-form-item>
      <el-form-item label="替换变量" prop="replace_variables">
        <el-switch v-model="form.replace_variables" active-value="Y" inactive-value="N"></el-switch>
      </el-form-item>
      <el-form-item label="单条SQL语句" prop="single_statement">
        <el-switch v-model="form.single_statement" active-value="Y" inactive-value="N"></el-switch>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
      <dialog-footer @cancel="cancel" @ok="submitForm" ok-text="保存">
        <el-button type="success" @click="active = 2">下一步</el-button>
      </dialog-footer>
    </div>

    <div v-show="active === 2" class="step2">
      <el-form-item label="创建新脚本">
        <el-radio-group v-model="form.selectScriptStatus">
          <el-radio label="是"/>
          <el-radio label="否，选择已有脚本"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择脚本" v-if="form.selectScriptStatus === '否，选择已有脚本'">
        <el-select v-model="form.scriptName" @change="handleScriptChange">
          <el-option
              v-for="item in scriptList"
              :key="item.id"
              :label="item.scriptName"
              :value="item.scriptName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SQL">
        <monaco-editor style="width:100%; height:400px"
                       v-model:value="form.sql"
                       @changeTextArea="changeTextArea"
                       ref="monacoEditorRef"
                       class="script-textarea"
                       language='Sql'
        ></monaco-editor>
      </el-form-item>
      <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
        <el-button type="success" @click="active = 1">上一步</el-button>
      </dialog-footer>
    </div>
  </el-form>
</template>

<script setup>
import {defineComponent, onMounted, reactive, ref, watch} from 'vue';
import {flowServiceStore} from '@data/store/flow';
import {storeToRefs} from 'pinia';
import monacoEditor from "../disposition/monaco-editor.vue";
import {search as datasourceList} from '@data/api/data/datasource'
import {selectTables,selectSchema} from '@data/api/data/datacollection'

const flowCount = flowServiceStore();

const {flowData} = storeToRefs(flowCount);

const monacoEditorRef = ref(null);

defineComponent({
  name: 'ExecSQL',
});

const props = defineProps({
  detailObject: {
    type: Object,
    default: () => {
    },
  },
})

const steps = ref([
  { value: 1, title: '基本属性' },
  { value: 2, title: 'SQL语句' }
]);
const active = ref(1);

const rDsList = ref([]);
const rTbList = ref([]);
const schemaList = ref([]);
const loading = ref(false);

const form = reactive({
  nodeName: '',
  name: '',
  type: 'ExecSQL',
  distribute: 'Y',
  copies: 1,
  connection: '',
  execute_each_row: '',
  single_statement: '',
  replace_variables: '',
  quoteString: '',
  isStream: '',

  selectScriptStatus: '',
  scriptName: '',
  sql: '',
  sqlValue:'',
  set_params: '',
  remark: '',

  insert_field: '',
  update_field: '',
  delete_field: '',
  read_field: '',
  arguments: {
    argument: [],
  },


  GUI: {
    xloc: 1,
    yloc: 1,
    draw: 'Y'
  }
});

const emit = defineEmits(['cancel', 'update-data']);

onMounted(() => {
  getJdbcDs();
  form.nodeName = flowData.value[props.detailObject.id]?.nodeName || props.detailObject.data.label;
  form.name = props.detailObject.id;
  form.typeConcatName = `${props.detailObject.id}(${form.type}-${props.detailObject.id})`;
  form.arguments = flowData.value[props.detailObject.id]?.arguments || {
    argument: [],
  };
  form.datasourceId = flowData.value[props.detailObject.id]?.datasourceId || '';
  form.datasourceType = flowData.value[props.detailObject.id]?.datasourceType || '';
  form.connection = flowData.value[props.detailObject.id]?.connection || '';
  form.schema = flowData.value[props.detailObject.id]?.schema || '';
  form.table = flowData.value[props.detailObject.id]?.table || '';
  form.execute_each_row = flowData.value[props.detailObject.id]?.execute_each_row || 'Y';
  form.replace_variables = flowData.value[props.detailObject.id]?.replace_variables || '';
  form.single_statement = flowData.value[props.detailObject.id]?.single_statement || '';
  form.remark = flowData.value[props.detailObject.id]?.remark || '';

  form.selectScriptStatus = flowData.value[props.detailObject.id]?.selectScriptStatus || '是';
  form.scriptName = flowData.value[props.detailObject.id]?.scriptName || '';
  form.sql = flowData.value[props.detailObject.id]?.sql || '';
  form.sqlValue = flowData.value[props.detailObject.id]?.sqlValue || '';
  monacoEditorRef.value.setData(form.sql);


  form.isStream = flowData.value[props.detailObject.id]?.isStream || '';

  form.distribute = flowData.value[props.detailObject.id]?.distribute || 'Y';

})

watch(() => form.datasourceId, (newVal, oldVal) => {
  if (form.datasourceType === 'postgresql' || form.datasourceType === 'oracle') {
    getSchema()
  } else {
    getTables();
  }
});

const rDsChange = (e) => {
  // 清空
  form.table = '';
  rDsList.value.find((item) => {
    if (item.datasourceId === e) {
      form.datasourceType = item.datasourceType;
      form.connection = item.datasourceCode;
    }
  })
}

const getJdbcDs = () => {
  loading.value = true
  datasourceList({}).then(response => {
    const {list} = response.data
    rDsList.value = list //list.filter( item => item.jdbcUrl.includes('oracle'))
    loading.value = false
  })
}

const getSchema =() =>{
  const obj = {
    datasourceId: form.datasourceId
  }
  selectSchema(obj).then(response => {
    schemaList.value = response.data
  })
}

const schemaChange =(e)=> {
  form.schema = e
  // 获取可用表
  getTables()
}

// 获取表名
const getTables = () => {
  if (form.datasourceId) {
    let obj = {
      datasourceId: form.datasourceId
    }
    if(form.datasourceType == 'postgresql'  || form.datasourceType == 'oracle'){
      obj.tableSchema = form.schema;
    }
    // 组装
    loading.value = true
    selectTables(obj).then(response => {
      if (response) {
        loading.value = false
        rTbList.value = response.data
      }
    })
  }

}

const changeTextArea = (value) => {
  console.log(value)
  form.sqlValue = value;
}

const submitForm = () => {
  form.fields.field.forEach(fieldItem => {
    form.fieldList.push(fieldItem);
  });
  form.sql = form.sqlValue
  flowCount.setFlowData(
      {
          ...flowData.value,
          [props.detailObject.id]: {
              ...form,
              name: `${form.type}-${form.name}`,
          }
      }
  )

  // 触发数据更新事件
  // emit('update-data', {
  //   id: props.detailObject.id,
  //   data: form
  // });

  // console.log("flowData",flowData.value);
  // emit('getComponentId', props.detailObject.id)
  emit('cancel');

}

const cancel = () => {
  emit('cancel');
}

const toReader = () => {

}

const parseSql = () => {
}

</script>

<style>

</style>